using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    public int playerIndex;
    public KeyCode leftKey;
    public KeyCode rightKey;
    public KeyCode jumpKey;
    public KeyCode diveKey;
    public List<KeyCode> keys;
    public string reverseAudio;
    public List<string> skillAudios;
    public List<string> defenseAudios;

    private PlayerController m_ctrller;
    private Animator m_animator;
    private Glove[] m_gloves;
    private int m_curHP;
    private float m_invincibleTime;
    public int HP
    {
        get
        {
            return m_curHP;
        }
    }
    public Vector3 Pos
    {
        get
        {
            return m_ctrller.transform.position;
        }
    }
    public Transform body
    {
        get
        {
            return m_ctrller.transform;
        }
    }

    private void Awake()
    {
        //GameManager.Instance.AssignPlayer(playerIndex, this);

        m_curHP = 5;

        m_ctrller = GetComponentInChildren<PlayerController>();
        m_ctrller.LeftKey = leftKey;
        m_ctrller.RightKey = rightKey;
        m_ctrller.JumpKey = jumpKey;
        m_ctrller.DiveKey = diveKey;

        m_animator = m_ctrller.GetComponentInChildren<Animator>();

        m_gloves = GetComponentsInChildren<Glove>();
        for (int i = 0; i < keys.Count; i++)
        {
            m_gloves[i].fireKey = keys[i];
            m_gloves[i].playerIndex = playerIndex;
            m_gloves[i].playerOffset = transform.position;
            m_gloves[i].fireAudios = skillAudios;
        }
    }

    private void Update()
    {
        if (GameManager.Instance.isPause)
            return;

        m_invincibleTime -= Time.deltaTime;
    }

    public void Reverse()
    {
        if (reverseAudio.Length > 0)
            AudioManager.Instance.PlaySE(reverseAudio);

        m_curHP++;
        m_curHP = Mathf.Min(m_curHP, 10);
        m_ctrller.transform.localScale = Vector3.one * (0.7f + m_curHP * 0.06f);
    }

    public bool Damage()
    {
        if (m_invincibleTime > 0.0f)
            return false;

        m_invincibleTime = 0.3f;
        m_curHP--;
        m_curHP = Mathf.Max(0, m_curHP);
        m_ctrller.transform.localScale = Vector3.one * (0.7f + m_curHP * 0.06f);
        if (GameManager.Instance.CheckGameOver())
        {
            Dead();
            return false;
        }

        //受击动画
        m_animator.SetTrigger("Hit");
        var randomIndex = Random.Range(0, defenseAudios.Count);
        AudioManager.Instance.PlaySE(defenseAudios[randomIndex]);
        return true;
    }

    public void SetHP(int newHP)
    {
        m_curHP = newHP;
    }

    public void Dead()
    {
        m_curHP = 0;
        m_animator.SetBool("Dead", true);
        GameManager.Instance.GameOver();
    }
}
